<template>
  <div>
    <van-nav-bar left-arrow @click-left="onClickLeft" title="订单编辑" />

    <div class="pb-[50px]">
      <!-- 发货信息表单 -->
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <template #title>
            <div class="flex justify-between">
              <span>发货信息</span>
              <span class="text-blue-500" @click="showSendAddress = true"
                >选择记录</span
              >
            </div>
          </template>
          <van-field
            v-model="sendUser.name"
            label="发货人"
            placeholder="请输入发货人"
            :rules="[{ required: true, message: '请填写发货人' }]"
          />

          <van-field
            v-model="sendUser.phone"
            label="联系电话"
            placeholder="请输入发货人联系电话"
            :rules="[{ required: true, message: '请填写发货人联系电话' }]"
          />

          <van-field
            v-model="sendUser.region"
            readonly
            clickable
            label="发货地区"
            placeholder="请选择发货地区"
            right-icon="arrow"
            @click="onShowAddressPicker('sendUser.region')"
            :rules="[{ required: true, message: '请选择发货地区' }]"
          />

          <!-- 省市区 -->
          <van-popup v-model:show="showAddressPicker" position="bottom">
            <van-area
              :areaList="areaList"
              @confirm="onAddressConfirm"
              @cancel="showAddressPicker = false"
            />
          </van-popup>

          <van-field
            v-model="sendUser.town"
            label="街道"
            clearable
            placeholder="请输入街道"
            :rules="[{ required: true, message: '请填写街道' }]"
          />

          <van-field
            v-model="sendUser.address"
            label="详细地址"
            type="textarea"
            rows="1"
            autosize
            clearable
            placeholder="请输入详细地址"
            :rules="[{ required: true, message: '请填写详细地址' }]"
          />

          <van-field
            v-model="sendUser.unitName"
            label="发货公司"
            placeholder="请输入发货公司"
            :rules="[{ required: true, message: '请填写发货公司' }]"
          />

          <!-- <van-field
          v-model="sendUser.unitCity"
          readonly
          label="公司地区"
          placeholder="请选择发货公司地区"
          right-icon="arrow"
          @click="onShowAddressPicker('sendUser.unitCity')"
        /> -->

          <van-field
            v-model="sendUser.unitPhone"
            label="发货公司电话"
            placeholder="请输入发货公司联系电话"
            :rules="[{ required: true, message: '请填写发货公司联系电话' }]"
          />

          <van-field
            v-model="sendUser.unitAddress"
            label="发货公司地址"
            type="textarea"
            rows="1"
            autosize
            clearable
            placeholder="请输入发货公司地址"
            :rules="[{ required: true, message: '请填写发货公司地址' }]"
          />
        </van-cell-group>

        <van-cell-group inset>
          <template #title>
            <div class="flex justify-between">
              <span>收货信息</span>
              <span class="text-blue-500" @click="showReceiveAddress = true"
                >选择记录</span
              >
            </div>
          </template>
          <van-field
            v-model="resivceUser.username"
            label="收货人"
            placeholder="请输入收货人"
            :rules="[{ required: true, message: '请填写收货人' }]"
          />

          <van-field
            v-model="resivceUser.phone"
            label="联系电话"
            placeholder="请输入收货人联系电话"
            :rules="[{ required: true, message: '请填写收货人联系电话' }]"
          />

          <van-field
            readonly
            label="收货地区"
            v-model="resivceUser.region"
            placeholder="请选择收货地区"
            right-icon="arrow"
            @click="onShowAddressPicker('resivceUser.region')"
            :rules="[{ required: true, message: '请填写收货地区' }]"
          />

          <van-field
            v-model="resivceUser.town"
            label="收货街道"
            clearable
            placeholder="请输入收货街道"
            :rules="[{ required: true, message: '请填写收货街道' }]"
          />

          <van-field
            v-model="resivceUser.address"
            label="详细地址"
            type="textarea"
            rows="1"
            autosize
            clearable
            placeholder="请输入收货详细地址"
            :rules="[{ required: true, message: '请填写收货详细地址' }]"
          />

          <van-field
            v-model="resivceUser.unitName"
            label="收货公司"
            placeholder="请输入收货公司"
          />

          <van-field
            readonly
            v-model="resivceUser.unitCity"
            label="公司地区"
            placeholder="请选择收货公司地区"
            right-icon="arrow"
            @click="onShowAddressPicker('resivceUser.unitCity')"
          />
          <van-field
            v-model="resivceUser.unitPhone"
            label="收货公司电话"
            placeholder="请输入收货公司联系电话"
          />
          <van-field
            v-model="resivceUser.unitAddress"
            label="收货公司地址"
            type="textarea"
            rows="1"
            autosize
            clearable
            placeholder="请输入收货公司详细地址"
          />
        </van-cell-group>

        <van-cell-group inset title="货物信息">
          <van-field
            v-model="cargo.cargoName"
            label="货物名称"
            placeholder="请输入货物名称"
            clearable
            :rules="[{ required: true, message: '请填写货物名称' }]"
          />

          <van-field
            v-model="cargo.totalPackages"
            label="包装件数"
            placeholder="请输入包装件数"
            type="number"
            clearable
            :rules="[{ required: true, message: '请填写包装件数' }]"
          />

          <van-field
            v-model="cargo.volume"
            label="体积"
            type="number"
            placeholder="请输入货物体积"
            clearable
          >
            <template #extra>
              <span>m³</span>
            </template>
          </van-field>

          <van-field
            v-model="cargo.weight"
            label="重量"
            type="number"
            placeholder="请输入货物重量"
            clearable
            :rules="[{ required: true, message: '请填写货物重量' }]"
          >
            <template #extra>
              <span>KG</span>
            </template>
          </van-field>

          <van-field
            v-model="cargo.pickupWay"
            label="送货方式"
            placeholder="请选择送货方式"
            readonly
            right-icon="arrow"
            @click="showPickupWayPicker = true"
          />

          <van-popup v-model:show="showPickupWayPicker" round position="bottom">
            <van-picker
              :columns="pickupWaycolumns"
              @cancel="showPickupWayPicker = false"
              @confirm="onPickupWayConfirm"
            />
          </van-popup>

          <van-field
            v-model="cargo.insuranceValue"
            label="报价金额"
            placeholder="请输入报价金额"
            clearable
            :rules="[{ required: true, message: '请填写报价金额' }]"
          >
            <template #extra>
              <span>元</span>
            </template>
          </van-field>

          <van-field
            v-model="cargo.goodMode"
            label="收货方式"
            placeholder="请选择收货方式"
            readonly
            right-icon="arrow"
            @click="showGoodModePicker = true"
          />

          <van-popup v-model:show="showGoodModePicker" round position="bottom">
            <van-picker
              :columns="goodModecolumns"
              @cancel="showGoodModePicker = false"
              @confirm="onGoodModeConfirm"
            />
          </van-popup>
        </van-cell-group>
        <!-- 下单 -->
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>

      <SendUserAddressList
        v-model:show="showSendAddress"
        @confirm="selectSendUser"
      />
      <ReceiveUserAddressList
        v-model:show="showReceiveAddress"
        @confirm="selectReceiveUser"
      />
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
import { showFailToast, showLoadingToast, showToast } from "vant";
import { areaList } from "@vant/area-data";
import { orderUpdateOrder, orderQueryById } from "@/api/order";
import { useRoute, useRouter } from "vue-router";
import SendUserAddressList from "@/components/SendUserAddressList.vue";
import ReceiveUserAddressList from "@/components/ReceiveUserAddressList.vue";

export default {
  components: {
    SendUserAddressList,
    ReceiveUserAddressList,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const cacheUser = ref({});
    const sendUser = ref({
      name: "",
      region: "",
      prov: "",
      city: "",
      area: "",
      town: "",
      address: "",
      phone: "",
      unitName: "",
      unitAddress: "",
      unitPhone: "",
    });
    const resivceUser = ref({
      username: "",
      region: "",
      prov: "",
      city: "",
      area: "",
      town: "",
      address: "",
      phone: "",
      unitName: "",
      unitCity: "",
      unitAddress: "",
      unitPhone: "",
    });
    const cargo = ref({
      cargoName: "",
      totalPackages: "",
      volume: "",
      pickupWay: "",
      insuranceValue: "",
      goodMode: "",
      weight: "",
    });
    const showSendAddress = ref(false);
    const showReceiveAddress = ref(false);

    const type = ref("");

    const showPickupWayPicker = ref(false);
    const showGoodModePicker = ref(false);
    const showAddressPicker = ref(false);

    const pickupWaycolumns = ref([
      { text: "自提", value: "自提" },
      { text: "送货上楼（无电梯）", value: "送货上楼（无电梯）" },
      { text: "送货上楼（有电梯）", value: "送货上楼（有电梯）" },
      { text: "送货（不含上楼）", value: "送货（不含上楼）" },
    ]);
    const goodModecolumns = ref([
      { text: "客户自送", value: "客户自送" },
      { text: "上门接货", value: "上门接货" },
    ]);

    const onShowAddressPicker = (t) => {
      showAddressPicker.value = true;
      type.value = t;
    };

    const onSubmit = async () => {
      const loading = showLoadingToast("提交中...");
      try {
        const params = {
          ...cacheUser.value,
          resivceUser: resivceUser.value,
          sendUser: sendUser.value,
          cargo: cargo.value,
        };
        const { success, message } = await orderUpdateOrder(params);

        loading.close();

        if (success) {
          showToast({
            message: "修改成功！",
            forbidClick: true,
            type: "success",
            onClose: () => router.replace("/order/list"),
          });
        } else {
          showFailToast(message);
        }
      } catch {
        loading.close();
      }
    };

    const onAddressConfirm = ({ selectedOptions }) => {
      const str = selectedOptions.map((item) => item.text).join("/");
      if (type.value == "sendUser.region") {
        sendUser.value.region = str;
        sendUser.value.prov = selectedOptions[0].text;
        sendUser.value.city = selectedOptions[1].text;
        sendUser.value.area = selectedOptions[2].text;
      } else if (type.value == "sendUser.unitCity") {
        sendUser.value.unitCity = str;
      } else if (type.value == "resivceUser.region") {
        resivceUser.value.region = str;
        resivceUser.value.prov = selectedOptions[0].text;
        resivceUser.value.city = selectedOptions[1].text;
        resivceUser.value.area = selectedOptions[2].text;
      } else {
        resivceUser.value.unitCity = str;
      }
      showAddressPicker.value = false;
    };
    const onPickupWayConfirm = ({ selectedOptions }) => {
      cargo.value.pickupWay = selectedOptions[0].text;
      showPickupWayPicker.value = false;
    };
    const onGoodModeConfirm = ({ selectedOptions }) => {
      cargo.value.goodMode = selectedOptions[0].text;
      showGoodModePicker.value = false;
    };

    const selectSendUser = (user) => {
      Object.assign(sendUser.value, user);
      sendUser.value.region = `${user.prov}/${user.city}/${user.area}`;
    };
    const selectReceiveUser = (user) => {
      Object.assign(resivceUser.value, user);
      resivceUser.value.region = `${user.prov}/${user.city}/${user.area}`;
    };

    const onClickLeft = () => router.replace("/order/list");

    onMounted(async () => {
      const loading = showLoadingToast("加载中...");
      try {
        const { result } = await orderQueryById(route.params.orderId);

        loading.close();

        selectSendUser(result.sendUser);
        selectReceiveUser(result.resivceUser);
        Object.assign(cargo.value, result.cargo);

        cacheUser.value = result;
      } catch {
        loading.close();
        showFailToast("获取数据失败");
      }
    });

    return {
      sendUser,
      resivceUser,
      cargo,
      areaList,
      showSendAddress,
      showReceiveAddress,
      showAddressPicker,
      showPickupWayPicker,
      showGoodModePicker,
      pickupWaycolumns,
      goodModecolumns,
      onAddressConfirm,
      onPickupWayConfirm,
      onShowAddressPicker,
      onGoodModeConfirm,
      selectSendUser,
      selectReceiveUser,
      onClickLeft,
      onSubmit,
    };
  },
};
</script>
